using System.Data;
using Microsoft.Extensions.Options;
using SPI.AgentServer.Configuration;
using SPI.AgentServer.Services.Execution;

namespace SPI.AgentServer.Services.Tools;

/// <summary>
/// 设备统计工具 - 统计设备数量和状态
/// </summary>
public class GetDeviceStatsTool : IQueryTool
{
    private readonly IDatabaseExecutor _executor;
    private readonly DatabaseConfiguration _config;
    private readonly ILogger<GetDeviceStatsTool> _logger;

    public string Name => "get_device_stats";
    public string Description => "获取设备统计信息，包括总数、在线数、离线数、异常数等";

    public GetDeviceStatsTool(
        IDatabaseExecutor executor,
        IOptions<DatabaseConfiguration> options,
        ILogger<GetDeviceStatsTool> logger)
    {
        _executor = executor;
        _config = options.Value;
        _logger = logger;
    }

    public async Task<ToolResult> ExecuteAsync(Dictionary<string, object> parameters, CancellationToken cancellationToken = default)
    {
        if (!ValidateParameters(parameters, out var errors))
        {
            return new ToolResult
            {
                Success = false,
                Errors = errors
            };
        }

        try
        {
            var deviceType = parameters.ContainsKey("deviceType") ? parameters["deviceType"]?.ToString() : null;
            var areaId = parameters.ContainsKey("areaId") ? parameters["areaId"]?.ToString() : null;

            // 构建 SQL 查询
            var sql = @"
SELECT
    COUNT(*) as TotalCount,
    SUM(CASE WHEN OnLineStatus = 1 THEN 1 ELSE 0 END) as OnlineCount,
    SUM(CASE WHEN OnLineStatus = 0 OR OnLineStatus IS NULL THEN 1 ELSE 0 END) as OfflineCount,
    SUM(CASE WHEN ExceptionStatus = 1 THEN 1 ELSE 0 END) as ExceptionCount,
    SUM(CASE WHEN AlarmStatus = 1 THEN 1 ELSE 0 END) as AlarmCount
FROM tbldevice
WHERE IsValid = 1";

            // 添加筛选条件
            if (!string.IsNullOrEmpty(deviceType))
            {
                sql += $" AND DeviceTypeId = '{deviceType}'";
            }

            if (!string.IsNullOrEmpty(areaId))
            {
                sql += $" AND StationAreaId = '{areaId}'";
            }

            _logger.LogInformation("Executing device stats query: {Sql}", sql);

            var result = await _executor.ExecuteQueryAsync(sql, null, cancellationToken);

            return new ToolResult
            {
                Success = true,
                Data = result.Data,
                Message = "设备统计信息查询成功",
                Metadata = new Dictionary<string, object>
                {
                    ["executionTimeMs"] = result.ExecutionTimeMs,
                    ["executedSql"] = sql
                }
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error executing device stats query");
            return new ToolResult
            {
                Success = false,
                Errors = new List<string> { $"查询错误: {ex.Message}" }
            };
        }
    }

    public bool ValidateParameters(Dictionary<string, object> parameters, out List<string> errors)
    {
        errors = new List<string>();
        // 此工具不需要必填参数，所有参数都是可选的
        return true;
    }
}
